import { useRef, useState } from 'react';
import { Input, Button, Popconfirm, Space, message } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import { zhimaListApi } from '@/api';
import { isSuccess } from '@/utils';
import dayjs from 'dayjs';
import AddZhiMa from './AddZhiMa';

export default function ZhiMa() {
  const wait = () => new Promise((resolve) => setTimeout(resolve, 1000));
  const tableRef: any = useRef('');
  const [open, setOpen] = useState(false);
  const [formData, setFormData] = useState({});

  // 打开弹框
  function openModal(data: any = {}) {
    setOpen(true);
    setFormData(data);
  }

  // 请求
  const request = async (params: any) => {
    params.pageNum = params.current;
    const res: any = await zhimaListApi(params);
    if (!isSuccess(res)) return { data: [], total: 0 };
    return { data: res?.data?.list, total: res?.data?.total, success: true };
  };

  const columns: ProColumns[] = [
    {
      title: '芝麻账户',
      dataIndex: 'name',
    },
    {
      title: 'apiKey',
      dataIndex: 'key',
    },
    {
      title: 'apiSecret',
      dataIndex: 'secret',
    },
    {
      title: '账户余额',
      dataIndex: 'balance',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      hideInSearch: true,
      render: (text: any) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      hideInSearch: true,
      render: (text: any) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      render: (text: any) => (
        <div className={` ${text ? 'color-green' : 'color-red'}`}>{text ? '开' : '关'}</div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      width: 140,
      fixed: 'right',
      render: (_: any, record: any) => [
        <div key="opt" style={{ marginLeft: -8 }}>
          <Button type="link" size="small" onClick={() => openModal(record)}>
            编辑
          </Button>
        </div>,
      ],
    },
  ];

  // 删除
  const deleteFn = async (id: number) => {
    tableRef.current.reload();
  };

  return (
    <>
      <ProTable
        headerTitle="账户列表"
        rowKey="id"
        columns={columns}
        request={request}
        actionRef={tableRef}
        search={false}
        options={false}
        scroll={{ x: 1300 }}
        toolBarRender={() => [<Button onClick={() => openModal({})}>新增账户</Button>]}
      />
      <AddZhiMa
        open={open}
        setOpen={setOpen}
        formData={formData}
        reload={tableRef?.current?.reload}
      />
    </>
  );
}
